<template>
  <div class="app-container pagination">
    <el-card>
      <div class="header">
        <div>
          <el-input v-model="search['search']" placeholder="请输入司机姓名或手机号" class="search-input"/>
          <el-button type="primary" icon="el-icon-search" @click="()=>pagination['load']()">搜索</el-button>
        </div>
        <div>
          <router-link to="./add">
            <el-button type="primary" icon="el-icon-plus" class="margin-right-10">添加司机</el-button>
          </router-link>
          <el-button type="info" icon="el-icon-tickets" class="margin-right-10"><a :href="downloadTemplateUrl" target="_blank">导入模板</a></el-button>
          <el-upload
            ref="upload"
            :limit="1"
            :show-file-list="false"
            :http-request="uploadFiles"
            :before-upload="beforeUpload"
            class="upload"
            accept=".xls,.xlsx"
            action="">
            <el-button :loading="uploadLoading" type="primary" icon="el-icon-printer">批量导入</el-button>
          </el-upload>
        </div>
      </div>
      <ws-pagination v-model="pagination">
        <el-table-column prop="id" label="ID" width="90" header-align="center" align="center"/>
        <el-table-column prop="nickname" label="姓名" width="150" header-align="center" align="center"/>
        <el-table-column prop="genderText" label="性别" width="100" header-align="center" align="center"/>
        <el-table-column prop="mobile" label="手机号" width="200" header-align="center" align="center"/>
        <el-table-column prop="addTime" label="加入时间" width="200" header-align="center" align="center"/>
        <el-table-column prop="vehicleText" label="驾驶车型" min-width="160" header-align="center" align="center"/>
        <el-table-column prop="status" label="状态" width="120" header-align="center" align="center" fixed="right">
          <template slot-scope="scope">
            <div @click="changeStatus(scope.row)">
              <el-tag :type="scope.row.status===1?'success':'info'">{{ scope.row.status===1?'已上线':'已下线' }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" header-align="center" align="center" fixed="right">
          <template slot-scope="scope">
            <!--详情-->
            <!--<router-link :to="`./details?id=${scope['row']['id']}`">
              <el-button size="small" type="primary" icon="el-icon-search" circle/>
            </router-link>-->
            <!--编辑-->
            <router-link :to="`./edit?id=${scope['row']['id']}`">
              <el-button size="small" type="primary" icon="el-icon-edit" circle/>
            </router-link>
            <!--删除-->
            <el-button size="small" type="danger" icon="el-icon-delete" circle @click="deleteRow(scope['row'])"/>
          </template>
        </el-table-column>
      </ws-pagination>
    </el-card>
  </div>
</template>

<script>
  import Config from '../../../config';
  export default {
    name: 'InvoiceList',
    components: {},
    data() {
      return {
        // 查询条件
        search: {
          // 搜索内容
          search: '',
          // 状态
          status: ''
        },
        pagination: {},

        // 模板下载地址
        downloadTemplateUrl: `${Config['API_TYPE'] === 'prod' ? Config['API_PATH'] : Config['API_PATH_DEV']}` + '/admin/driver/downTemplate?token=' + this.$store.getters.token + '&mallId=' + this.$store.getters.sysUser.mallId,
        // 上传loading
        uploadLoading: false
      }
    },
    watch: {},
    created() {
      // 初始化分页器
      this.initPagination();
    },
    methods: {
      // 初始化分页器
      initPagination() {
        // 创建分页器
        this.pagination = new this.$pagination(async (...args) => {
          // 加载分页列表
          const result = await this.$service.applicationGetDriverList({
            ...args[0],
            name: this.search.search,
            status: this.search.status
          });
          if (result.code !== 0) {
            return this.$message.error(result.msg || '系统错误');
          }
          return result;
        });
        // 加载分页数据
        this.pagination.load();
      },

      // 切换上下架状态
      changeStatus({id, status}) {
        this.$confirm(`你确定要${status === 1 ? '下线' : '上线'}这个司机吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: async (confirm) => {
            if (confirm === 'confirm') {
              const result = await this.$service.applicationChangeDriverStatus({
                id: id,
                status: status === 1 ? 2 : 1
              });
              if (result.code === 0) {
                this.$message.success(`${status === 1 ? '下线' : '上线'}成功~`);
                // 加载分页数据
                this.pagination.load();
              } else {
                this.$message.error(result.msg);
              }
            }
          }
        });
      },

      // 删除指定行
      deleteRow({id}) {
        this.$confirm('此操作将删除该司机, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: async (confirm) => {
            if (confirm === 'confirm') {
              const result = await this.$service.applicationDeleteDriver({id: id});
              if (result.code === 0) {
                this.$message.success(`删除成功~`);
                // 加载分页数据
                this.pagination.load();
              } else {
                this.$message.error(result.msg);
              }
            }
          }
        });
      },
      // 文件上传之前
      beforeUpload(file) {
        const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        if (!isExcel) {
          this.$message.error('导入失败,请检查导入的文件是否是.xlsx或.xls文件')
        }
        return isExcel
      },
      // 文件上传
      uploadFiles(item) {
        this.$service.fileToBase64(item.file).then(async res => {
          this.uploadLoading = true;
          const result = await this.$service.adminFileUpload({file: res});
          if (result.code === 0) {
            this.$refs.upload.clearFiles(); // 上传成功之后清除历史记录
            this.importDriverData(result.data.url)
          }
          this.uploadLoading = false;
        });
      },
      // 导入司机数据
      importDriverData(address) {
        (async () => {
          this.uploadLoading = true;
          const result = await this.$service.applicationImportDriverData({address: address});
          if (result.code === 0) {
            this.$message.success('导入成功~');
            // 加载分页数据
            this.pagination.load();
          } else {
            this.$message.error(result.msg);
          }
        })();
      }
    }
  }
</script>

<style lang="scss" type="text/scss" scoped>
  @import '../../../styles/index.scss';
  .pagination {
    .header {
      @include flex-row(center, space-between);
      div{
        @include flex-row(center, flex-start);
        .search-input {
          width: 240px;
          margin-right: 5px;
        }
      }
    }
  }
</style>
